﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace AliIotLib
{
    public class AliIotDeviceManager: IIotDeviceManager
    {
        private readonly AliIotConfig _aliIotConfig;
        
        public AliIotDeviceManager(AliIotConfig aliIotConfig)
        {
            _aliIotConfig = aliIotConfig;
        }

        /// <summary>
        /// 注册单个设备。阿里物联网平台设备名称由平台自行执行
        /// </summary>
        /// <param name="device_name">设备名称，为空则由平台分配名称</param>
        /// <returns></returns>
        public AliIotRegisterDevice RegisterDevice(string device_name)
        {
            IClientProfile profile = DefaultProfile.GetProfile(_aliIotConfig.RegionId, _aliIotConfig.AccessKeyId, _aliIotConfig.AccessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = $"iot.{_aliIotConfig.RegionId}.aliyuncs.com";
            request.Version = "2018-01-20";
            request.Action = "RegisterDevice";
            request.AddQueryParameters("ProductKey", _aliIotConfig.ProductKey);
            if(!string.IsNullOrEmpty(device_name))
            {
                request.AddQueryParameters("DeviceName", device_name);
            }
            
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                if(response.HttpStatus==200)
                {
                    AliIotRequest<AliIotRegisterDevice> reponseContent = JsonConvert.DeserializeObject<AliIotRequest<AliIotRegisterDevice>>(response.Data);
                    if (reponseContent != null && reponseContent.Success)
                    {
                        return reponseContent.Data;
                    }
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }

            return null;
        }
        /// <summary>
        /// 批量注册设备
        /// </summary>
        /// <param name="device_name"></param>
        public bool BatchRegisterDevice()
        {
            return false;
        }
        /// <summary>
        /// 删除单个设备
        /// </summary>
        /// <param name="device_name"></param>
        public bool DeleteDevice(string DeviceName)
        {
            IClientProfile profile = DefaultProfile.GetProfile(_aliIotConfig.RegionId, _aliIotConfig.AccessKeyId, _aliIotConfig.AccessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = $"iot.{_aliIotConfig.RegionId}.aliyuncs.com";
            request.Version = "2018-01-20";
            request.Action = "DeleteDevice";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("ProductKey", _aliIotConfig.ProductKey);
            request.AddQueryParameters("DeviceName", DeviceName);
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                if(response.HttpStatus==200)
                {
                    if(!response.Data.Contains("ErrorMessage"))
                    {
                        AliIotRequestBase aliIotRequestBase = JsonConvert.DeserializeObject<AliIotRequestBase>(response.Data);
                        if(aliIotRequestBase.Success)
                        {
                            return true;
                        }
                    }
                   
                    return false;
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
            return false;
        }
        /// <summary>
        /// 向阿里云API接口查询单个设备的详细信息
        /// </summary>
        /// <param name="DeviceName"></param>
        /// <returns></returns>
        public AliIotDeviceDetail QueryDeviceDetail(string DeviceName)
        {
            try
            {
                IClientProfile profile = DefaultProfile.GetProfile(_aliIotConfig.RegionId, _aliIotConfig.AccessKeyId, _aliIotConfig.AccessKeySecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                CommonRequest request = new CommonRequest();
                request.Method = MethodType.POST;
                request.Domain = $"iot.{_aliIotConfig.RegionId}.aliyuncs.com";
                request.Version = "2018-01-20";
                request.Action = "QueryDeviceDetail";
                request.AddQueryParameters("ProductKey", _aliIotConfig.ProductKey);
                request.AddQueryParameters("DeviceName", DeviceName);

                CommonResponse response = client.GetCommonResponse(request);
                if (response.HttpStatus == 200)
                {
                    AliIotRequest<AliIotDeviceDetail> reponseContent = JsonConvert.DeserializeObject<AliIotRequest<AliIotDeviceDetail>>(response.Data);
                    if (reponseContent != null && reponseContent.Success)
                    {
                        return reponseContent.Data;
                    }
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }

            return null;
        }
        /// <summary>
        /// 按页码查询设备列表信息
        /// </summary>
        /// <param name="page">查询的页码</param>
        /// <returns></returns>
        public List<AliIotQueryDevice> QueryDevice(int page=1)
        {
            IClientProfile profile = DefaultProfile.GetProfile(_aliIotConfig.RegionId, _aliIotConfig.AccessKeyId, _aliIotConfig.AccessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = $"iot.{_aliIotConfig.RegionId}.aliyuncs.com";
            request.Version = "2018-01-20";
            request.Action = "QueryDevice";
            request.AddQueryParameters("ProductKey", _aliIotConfig.ProductKey);
            request.AddQueryParameters("CurrentPage", $"{page}");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                if (response.HttpStatus == 200)
                {
                    AliIotRequest<List<AliIotQueryDevice>> reponseContent = JsonConvert.DeserializeObject<AliIotRequest<List<AliIotQueryDevice>>>(response.Data);
                    if (reponseContent != null && reponseContent.Success)
                    {
                        return reponseContent.Data;
                    }
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }

            return null;
        }
    }
}
